<template>
  <view class="content pt-30 pb-50 pl-20 pr-20">
    <view class="detail-block pd-20">
      <view style="display: flex;">
        <view class="title-block">核查信息</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">隐患名称</view>
        <view class="item-value">{{detail.htName ? detail.htName : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">隐患等级</view>
        <view class="item-value">{{detail.levelName ? detail.levelName : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">隐患描述</view>
        <view class="item-value">{{detail.description ? detail.description : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">检查单位</view>
        <view class="item-value">{{detail.checkDept ? detail.checkDept : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">检查人</view>
        <view class="item-value">{{detail.checkPeo ? detail.checkPeo : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">检查类型</view>
        <view class="item-value">{{detail.checkType ? checkTypeJson[detail.checkType] : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">隐患地点</view>
        <view class="item-value">{{detail.place ? detail.place : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">所属风险点</view>
        <view class="item-value">{{detail.riskPoint ? detail.riskPoint : ''}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">所属单位</view>
        <view class="item-value">{{detail.beCheckDept ? detail.beCheckDept : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">整改方式</view>
        <view class="item-value">{{detail.rectificationType == 1 ? '限期整改' : '立即整改'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">整改责任单位</view>
        <view class="item-value">{{detail.rectificationDept ? detail.rectificationDept : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">整改责任人</view>
        <view class="item-value">{{detail.rectificationPeo ? detail.rectificationPeo : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">整改期限</view>
        <view class="item-value">{{detail.rectificationLimit ? detail.rectificationLimit : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">整改措施</view>
        <view class="item-value">{{detail.rectificationMeasure ? detail.rectificationMeasure : '-'}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common" v-if="detail.deferDate">
        <view class="item-label">延期时间</view>
        <view class="item-value">{{ detail.deferDate}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common" v-if="states == '1' ">
        <view class="item-label">剩余时间</view>
        <view class="item-value">{{getRemainingTime(nowDateTime, detail.rectificationLimit)}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common" v-if="states == '2'  ">
        <view class="item-label">剩余时间</view>
        <view class="item-value">{{getRemainingTime(nowDateTime, detail.deferDate)}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common" v-if="states == '99' ">
        <view class="item-label">剩余时间</view>
        <view class="item-value">{{getRemainingTime(nowDateTime, detail.checkDate)}}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common" v-if="detail.deferApproveResult">
        <view class="item-label">延期审批结果</view>
        <view class="item-value">{{detail.deferApproveResult }}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common" v-if="detail.deferApproveInfo">
        <view class="item-label">审批拒绝原因</view>
        <view class="item-value">{{detail.deferApproveInfo }}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common" v-if="detail.cancelInfo">
        <view class="item-label">验收驳回意见</view>
        <view class="item-value">{{detail.cancelInfo }}</view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">整改前图片</view>
        <view class="image-list">
          <image v-for="(item, index) in detail.ossImg" :key="index" class="image" mode="aspectFill" :src="item.url" @click="previewImage(item.url)"></image>
        </view>
      </view>
      <view class="item-block pt-20 pb-20 border-b-common">
        <view class="item-label">整改完成时间</view>
        <view class="item-value" @click="() => dateTimeState = true">
          <text v-if="params.rectificationDate" class="mr-10">{{params.rectificationDate}}</text>
          <text v-else class="item-default-text mr-10">请选择整改完成时间</text>
          <u-icon name="arrow-right" size="26rpx" color="#CCCCCC"></u-icon>
        </view>
      </view>
      <view class="item-block pt-20">
        <view class="item-label">整改后图片</view>
        <view class="image-list">
          <u-upload width="145" height="120" :action="action" multiple :max-count="3" :file-list="fileList" @afterRead="afterRead" @delete="deleteImage"></u-upload>
        </view>
      </view>
    </view>
    <view class="detail-block pd-20 mt-30">
      <view class="mb-20" style="display: flex;">
        <view class="title-block">整改完成结果</view>
      </view>
      <view>
        <textarea class="text-area pd-20" placeholder="请输入整改完成结果" placeholder-class="placeholder" v-model="params.rectificationResult"></textarea>
      </view>
    </view>
    <view class="button-block mt-30">
      <u-button type="info" text="取消" :custom-style="{width: '340rpx', backgroundColor: '#FFFFFF !important'}" @click="routeBack()"></u-button>
      <u-button type="primary" text="确认" :custom-style="{width: '340rpx'}" @click="submit"></u-button>
    </view>
    <u-datetime-picker :show="dateTimeState" v-model="rectificationDate" :closeOnClickOverlay="true" :maxDate="nowDateTime" mode="datetime" @confirm="dateTimeConfirm" @close="() => dateTimeState = false" @cancel="() => dateTimeState = false"></u-datetime-picker>
  </view>
</template>

<script>
  import { getDangerEditDetailApi, updateDangerEditInfoApi } from '@/apis/danger/index.js'
  import { getToken } from '@/utils/auth.js'
  import checkTypeJson from '@/static/json/checkType.json'
  import dayjs from 'dayjs'

  export default {
    data() {
      return {
        states:'',
        nowDateTime: dayjs().valueOf(),
        checkTypeJson,
        action: this.uploadImageUrl,
        fileList: [],
        detail: {},
        params: {
          rectificationOssImg: [],
          rectificationDate: dayjs().format('YYYY-MM-DD HH:mm:ss'),
          rectificationResult: ''
        },
        rectificationDate: dayjs().valueOf(),
        dateTimeState: false
      }
    },
    onLoad(options) {
      console.log(options)
      if(options.states) this.states = options.states
      if(options.id) this.getDangerEditDetail({id: options.id})
      console.log(this.states)
    },
    methods: {
      getDangerEditDetail: function(params) {
        getDangerEditDetailApi(params).then(res => {
          console.log('res', res)
          this.detail = res
          this.fileList = res.rectificationOssImg
          console.log(this.fileList)
        }).catch(err => console.warn(err))
      },
      submit: function() {
        if(!this.authFormData()) return false
        let params = this.params
        Object.assign(params, {id: this.detail.id, htId: this.detail.htId})
        updateDangerEditInfoApi(params).then(res => {
          setTimeout(() => uni.navigateBack(), 500)
        }).catch(err => console.log(err))
      },
      getRemainingTime: function(startTime = dayjs().format('YYYY-MM-DD HH:mm:ss'), endTime = dayjs().format('YYYY-MM-DD HH:mm:ss')) {
        if(dayjs(startTime).valueOf() < dayjs(endTime).valueOf()){
          var dayaa = dayjs(endTime).valueOf() - dayjs(startTime).valueOf()
          var days = parseInt(dayaa / (1000 * 60 * 60 * 24));
          var hours = parseInt((dayaa % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          return days + " 天 " + hours + " 小时 " ;
        }else{
          var dayaa = dayjs(startTime).valueOf() -  dayjs(endTime).valueOf()
          var days = parseInt(dayaa / (1000 * 60 * 60 * 24));
          var hours = parseInt((dayaa % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
          return "已逾期 "+ days + " 天 " + hours + " 小时 " ;
        }
        // return startTime && endTime && (dayjs(startTime).valueOf() < dayjs(endTime).valueOf()) ? dayjs(endTime).diff(startTime,'days:h') : 0
      },
      dateTimeConfirm: function(event) {
        this.params.rectificationDate = dayjs(event.value).format('YYYY-MM-DD HH:mm:ss')
        this.dateTimeState = false
      },
      previewImage: function(url) {
        uni.previewImage({ urls: [url] })
      },
      deleteImage(event) {
        this.fileList.splice(event.index, 1)
      },
      async afterRead(event) {
        // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
        let lists = [].concat(event.file)
        let fileListLen = this.fileList.length
        lists.map((item) => {
          this.fileList.push({
            ...item,
            status: 'uploading',
            message: '上传中'
          })
        })
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i].url)
          let item = this.fileList[fileListLen]
          if(result.status == 'success') {
            this.fileList.splice(fileListLen, 1, Object.assign(item, {
              status: result.status,
              message: '',
              url: result.url
            }))
            fileListLen++
          } else {
            this.fileList.splice(fileListLen, 1)
          }
        }
        console.log(this.fileList)
      },
      uploadFilePromise(url) {
        return new Promise((resolve, reject) => {
          let a = uni.uploadFile({
            url: this.uploadImageUrl,
            filePath: url,
            name: 'file',
            formData: {
              user: 'test'
            },
            header: {
              'Authorization': `Bearer ${getToken()}`,
              'tenant-id':  '1'
            },
            success: (res) => {
              let result = JSON.parse(res.data)
              if (result.code == 0) {
                this.params.rectificationOssImg.push(result.data)
                resolve({url: result.data.url, status: 'success'})
              } else {
                uni.showToast({ title: 'OSS服务器错误', icon: 'none' })
                resolve({url, status: 'fail'})
              }
            },
            fail: () => uni.showToast({ title: '图片上传失败', icon: 'none' })
          })
        })
      },
      deleteImage: function(event) {
        this.params.rectificationOssImg.splice(event.index, 1)
        this.fileList.splice(event.index, 1)
      },
      routeBack: function() {
        uni.navigateBack()
      },
      authFormData: function() {
        let params = this.params
        if(!params.rectificationDate) {
          uni.showToast({ title: '请选择整改完成时间', icon: 'none' })
          return false
        }
        if(!params.rectificationOssImg || params.rectificationOssImg.length <= 0) {
          uni.showToast({ title: '请上传整改后图片', icon: 'none' })
          return false
        }
        if(!params.rectificationResult) {
          uni.showToast({ title: '请输入整改完成结果', icon: 'none' })
          return false
        }
        return true
      }
    }
  }
</script>

<style>
  page {
    background-color: #F4F4F4;
  }
  .u-upload__wrap__preview__image {
    width: 160rpx !important;
    height: 160rpx !important;
  }
</style>

<style lang="scss" scoped>
  .content {
    .detail-block {
      border-radius: 6rpx;
      background-color: #FFFFFF;
      .title-block {
        font-size: 30rpx;
        line-height: 42rpx;
        color: #222222;
        font-weight: 500;
        background-image: linear-gradient(to bottom, rgba(0, 0, 0, 0), rgba(0, 0, 0, 0) 50%, #C5DBFF 50%, #C5DBFF);
      }
      .item-block {
        display: flex;
        align-items: center;
        justify-content: space-between;
        .item-label {
          font-size: 28rpx;
          line-height: 40rpx;
          color: #333333;
          .wraning-icon {
            color: #FE0303;
            margin-right: 5rpx;
          }
        }
        .item-value {
          font-size: 28rpx;
          line-height: 40rpx;
          color: #999999;
          max-width: 500rpx;
          display: flex;
          align-items: center;
        }
        .image-list {
          max-width: 520rpx;
          display: flex;
          justify-content: flex-end;
          flex-direction: row-reverse;
          flex-wrap: wrap;
          .image {
            width: 156rpx;
            height: 120rpx;
            border-radius: 6rpx;
            background-color: #CCCCCC;
            margin-left: 20rpx;
            margin-bottom: 20rpx;
          }
          .image:nth-child(3n) {
            margin-left: 0;
          }
        }
      }
      .text-area {
        width: 630rpx;
        height: 300rpx;
        font-size: 28rpx;
        line-height: 40rpx;
        color: #333333;
        border: 1rpx solid #EEEEEE;
        border-radius: 6rpx;
      }
      .placeholder {
        font-size: 28rpx;
        line-height: 40rpx;
        color: #999999;
      }
    }
    .button-block {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
  }
</style>
